package br.hm.operandroid.manager;

import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;

import android.content.Context;
import android.os.Build;
import br.hm.telephoneoperator.CallOperatorService;
import br.hm.telephoneoperator.yoegi.impl.YoegiCallOperationService;

public class ContactTelephoneOperatorManagerFactory {

	private static WeakReference<CallOperatorService> referenceCallOperatorService;

	public static ContactTelephoneOperatorManager getNewInstance(Context context) {

		String className;
		int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
		className = ContactTelephoneOperatorManagerFactory.class.getPackage()
				.getName();
		if (sdkVersion < Build.VERSION_CODES.ECLAIR) {
			className = className + ".Android1ContactTelephoneOperatorManager";
		} else {
			className = className + ".Android2ContactTelephoneOperatorManager";
		}
		try {
			Class<? extends ContactTelephoneOperatorManager> clazz = Class
					.forName(className).asSubclass(
							ContactTelephoneOperatorManager.class);
			Constructor<? extends ContactTelephoneOperatorManager> constructor = clazz
					.getConstructor(CallOperatorService.class, Context.class);

			CallOperatorService callOperatorService = null;
			if (referenceCallOperatorService == null) {
				callOperatorService = new YoegiCallOperationService();
				referenceCallOperatorService = new WeakReference<CallOperatorService>(
						callOperatorService);
			} else {
				callOperatorService = referenceCallOperatorService.get();
				if (callOperatorService == null) {
					callOperatorService = new YoegiCallOperationService();
					referenceCallOperatorService = new WeakReference<CallOperatorService>(
							callOperatorService);
				}
			}

			return constructor.newInstance(callOperatorService, context);
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}

	}

}
